<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>九宫格拼图</title>
	<script src="js/vue.global.js"></script>
	<style>
		* {
			padding: 0;
			margin: 0;
			box-sizing: border-box;
			list-style: none;
		}
		body {
			display: flex;
			flex-direction: column;
			align-items: center;
			font-family: Arial, sans-serif;
		}
		ul {
			width: 600px;
			height: 600px;
			display: flex;
			flex-wrap: wrap;
			margin-bottom: 20px;
		}
		li {
			width: 200px;
			height: 200px;
			background-image: url(img/bg.png);
			background-size: 600px;
			background-position: left top;
			border: 1px solid #fff;
			cursor: pointer;
		}
		.blank {
			background-image: none;
			cursor: default;
		}
		button {
			padding: 10px 20px;
			font-size: 16px;
			cursor: pointer;
			background-color: #4CAF50;
			color: white;
			border: none;
			border-radius: 5px;
			transition: background-color 0.3s;
		}
		button:hover {
			background-color: #45a049;
		}
	</style>
</head>
<body>
	<div id='app'>
		<ul>
			<li v-for='(item,index) in imgs' :key="index" :style="{backgroundPosition:item.pos}" :class="!item.pos ? 'blank':''" @click="move(index)">
				{{ item.id }}
			</li>
		</ul>
		<button @click="shuffle">开始游戏</button>
	</div>
	<script>
		Vue.createApp({
			data() {
				return {
					imgs: [
						{id: 1, pos: 'left top'},
						{id: 2, pos: 'center top'},
						{id: 3, pos: 'right top'},
						{id: 4, pos: 'left center'},
						{id: 5, pos: 'center'},
						{id: 6, pos: 'right center'},
						{id: 7, pos: 'left bottom'},
						{id: 8, pos: 'center bottom'},
						{id: 9, pos: ''} // 右下角图片隐藏
					],
					gameOver: false,
					winPositions: ['left top', 'center top', 'right top', 'left center', 'center', 'right center', 'left bottom', 'center bottom', '']
				};
			},
			methods: {
				shuffle() {
					let newImgs = this.imgs.slice();
					for (let i = newImgs.length - 1; i > 0; i--) {
						const j = Math.floor(Math.random() * (i + 1));
						[newImgs[i], newImgs[j]] = [newImgs[j], newImgs[i]];
					}
					this.imgs = newImgs;
					this.gameOver = false;
				},
				move(index) {
					if (this.gameOver) return;
					const emptyIndex = this.imgs.findIndex(item => !item.pos);
					if (this.canMove(index, emptyIndex)) {
						[this.imgs[index].pos, this.imgs[emptyIndex].pos] = [this.imgs[emptyIndex].pos, this.imgs[index].pos];
						this.checkWin();
					}
				},
				canMove(index, emptyIndex) {
					const x = index % 3;
					const y = Math.floor(index / 3);
					const emptyX = emptyIndex % 3;
					const emptyY = Math.floor(emptyIndex / 3);
					return (
						(Math.abs(x - emptyX) === 1 && y === emptyY) ||
						(Math.abs(y - emptyY) === 1 && x === emptyX)
					);
				},
				checkWin() {
					const currentPositions = this.imgs.map(item => item.pos);
					if (currentPositions.toString() === this.winPositions.toString()) {
						alert('恭喜你，挑战成功！');
						this.gameOver = true;
					}
				}
			}
		}).mount('#app');
	</script>
</body>
</html>